<template>
  <div class="page-box">
    <!-- 筛选条件 -->
    <div class="search-box">
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="handleDateChange">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-select v-model="searchForm.merchant_id" placeholder="请选择商户" clearable @change="handleMerchantChange">
            <el-option
              v-for="merchant in merchantOptions"
              :key="merchant.id"
              :label="merchant.merchant_name"
              :value="merchant.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select v-model="searchForm.campaign_id" placeholder="请选择活动" clearable :disabled="!searchForm.merchant_id">
            <el-option
              v-for="campaign in filteredCampaignOptions"
              :key="campaign.id"
              :label="campaign.campaign_name"
              :value="campaign.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadAnalyticsData"><i class="el-icon-search"></i></el-button>
          <el-button @click="resetSearch"><i class="el-icon-refresh-left"></i></el-button>
          <el-button type="success" @click="handleExport"><i class="el-icon-download"></i></el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon participation">
                <i class="el-icon-user"></i>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ participationStats.total_participations || 0 }}</div>
                <div class="stats-label">
                  总参与数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 480px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计用户通过NFC扫码参与活动的总次数，包括同一用户多次参与</div>
                      <div><strong>计算：</strong>SUM(参与记录数)，允许重复参与</div>
                      <div><strong>来源：</strong><code>consul_nfc_participations</code>（所有有效参与记录）</div>
                      <div><strong>筛选：</strong>受时间范围 / 商户 / 活动筛选限制</div>
                      <div style="margin-top: 8px; padding: 8px; background: #2c3e50; border-radius: 4px; color: #fff;">
                        <div><strong>💡 业务场景说明：</strong></div>
                        <div>张记小吃的NFC活动：</div>
                        <div>• 用户A扫码3次 = 3次参与</div>
                        <div>• 用户B扫码1次 = 1次参与</div>
                        <div>• 用户C扫码2次 = 2次参与</div>
                        <div><strong>总参与数 = 6次</strong>（所有扫码行为计数）</div>
                        <div style="color: #bdc3c7; font-size: 12px;">注：每次扫码参与都会被计入总数，体现活动热度</div>
                      </div>
                    </div>
                    <i class="el-icon-question stats-tip-icon"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon users">
                <i class="el-icon-s-custom"></i>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ participationStats.unique_users || 0 }}</div>
                <div class="stats-label">
                  独立用户数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 480px; line-height: 1.5;">
                      <div><strong>定义：</strong>参与活动的不重复用户数量，同一用户多次参与只计算一次</div>
                      <div><strong>计算：</strong>COUNT(DISTINCT user_id) 按用户去重统计</div>
                      <div><strong>来源：</strong><code>consul_nfc_participations</code>（按用户ID去重）</div>
                      <div><strong>筛选：</strong>受时间范围 / 商户 / 活动筛选限制</div>
                      <div><strong>对比：</strong>独立用户数 ≤ 总参与数，比值体现用户复参率</div>
                      <div style="margin-top: 8px; padding: 8px; background: #34495e; border-radius: 4px; color: #fff;">
                        <div><strong>💡 去重逻辑说明：</strong></div>
                        <div>张记小吃的NFC活动：</div>
                        <div>• 用户A扫码3次 → 算作1个独立用户</div>
                        <div>• 用户B扫码1次 → 算作1个独立用户</div>
                        <div>• 用户C扫码2次 → 算作1个独立用户</div>
                        <div><strong>独立用户数 = 3个</strong>（总参与6次 vs 独立用户3个）</div>
                        <div style="color: #bdc3c7; font-size: 12px;">注：复参率 = 6÷3 = 2.0，说明平均每人参与2次</div>
                      </div>
                    </div>
                    <i class="el-icon-question stats-tip-icon"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon conversion">
                <i class="el-icon-trophy"></i>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ conversionStats.conversion_rate || 0 }}%</div>
                <div class="stats-label">
                  转化率
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 480px; line-height: 1.5;">
                      <div><strong>定义：</strong>领奖码实际使用率，衡量活动最终转化效果</div>
                      <div><strong>计算：</strong>已使用领奖码数量 ÷ 总发放领奖码数量 × 100%</div>
                      <div><strong>来源：</strong><code>consul_wechat_reward_codes</code>（按状态统计）</div>
                      <div><strong>筛选：</strong>受时间范围 / 商户 / 活动筛选限制</div>
                      <div><strong>业务意义：</strong>转化率越高说明活动吸引力越强，用户参与度高</div>
                      <div style="margin-top: 8px; padding: 8px; background: #e67e22; border-radius: 4px; color: #fff;">
                        <div><strong>💡 转化流程说明：</strong></div>
                        <div>张记小吃的领奖码发放与使用：</div>
                        <div>• 扫码参与：100人次 → 发放100个领奖码</div>
                        <div>• 到店核销：65人 → 使用65个领奖码</div>
                        <div>• 未使用：35个（过期或放弃）</div>
                        <div><strong>转化率 = 65÷100 = 65%</strong></div>
                        <div style="color: #ecf0f1; font-size: 12px;">注：转化率直接反映活动的商业价值和用户粘性</div>
                      </div>
                    </div>
                    <i class="el-icon-question stats-tip-icon"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon campaigns">
                <i class="el-icon-s-flag"></i>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ participationStats.active_campaigns || 0 }}</div>
                <div class="stats-label">
                  活跃活动数
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 480px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计期内有用户参与的活动数量，只计算实际产生参与行为的活动</div>
                      <div><strong>计算：</strong>COUNT(DISTINCT campaign_id) WHERE 参与次数 > 0</div>
                      <div><strong>来源：</strong><code>consul_nfc_campaigns</code> JOIN <code>consul_nfc_participations</code></div>
                      <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                      <div><strong>活跃标准：</strong>至少有1次用户扫码参与记录</div>
                      <div style="margin-top: 8px; padding: 8px; background: #27ae60; border-radius: 4px; color: #fff;">
                        <div><strong>💡 活跃判定说明：</strong></div>
                        <div>张记小吃配置的活动：</div>
                        <div>• 春节优惠活动：10次参与 → ✅ 活跃</div>
                        <div>• 开业大酬宾：0次参与 → ❌ 非活跃</div>
                        <div>• 会员专享活动：5次参与 → ✅ 活跃</div>
                        <div><strong>活跃活动数 = 2个</strong>（已配置3个，实际活跃2个）</div>
                        <div style="color: #ecf0f1; font-size: 12px;">注：活跃率 = 2÷3 = 67%，反映活动设计的有效性</div>
                      </div>
                    </div>
                    <i class="el-icon-question stats-tip-icon"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 参与趋势图 -->
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>参与趋势</span>
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 520px; line-height: 1.5;">
                  <div><strong>定义：</strong>展示每日参与数和独立用户数的变化趋势</div>
                  <div><strong>双线含义：</strong></div>
                  <div>• <strong>参与数（蓝线）：</strong>每日扫码参与总次数，体现活动热度</div>
                  <div>• <strong>独立用户数（绿线）：</strong>每日参与的不重复用户数，体现用户覆盖面</div>
                  <div><strong>数据来源：</strong><code>consul_nfc_participations</code> 按日期统计</div>
                  <div><strong>筛选条件：</strong>受时间范围 / 商户 / 活动筛选限制</div>
                  <div style="margin-top: 8px; padding: 8px; background: #2c3e50; border-radius: 4px; color: #fff;">
                    <div><strong>💡 趋势分析技巧：</strong></div>
                    <div>• <strong>两线重合：</strong>每人只参与一次，新用户为主</div>
                    <div>• <strong>蓝线高于绿线：</strong>有复参行为，老用户活跃</div>
                    <div>• <strong>绿线突增：</strong>新用户大量涌入</div>
                    <div>• <strong>蓝线波动：</strong>活动推广效果变化</div>
                    <div style="color: #bdc3c7; font-size: 12px;">注：两线差距越大说明用户粘性越强</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;cursor:help;"></i>
              </el-tooltip>
            </div>
            <div id="trendChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 转化率饼图 -->
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <span>转化率分析</span>
              <el-tooltip placement="top">
                <div slot="content" style="max-width: 520px; line-height: 1.5;">
                  <div><strong>定义：</strong>饼图展示领奖码使用情况的占比分析</div>
                  <div><strong>双色含义：</strong></div>
                  <div>• <strong>绿色区域：</strong>已使用领奖码数量（成功转化）</div>
                  <div>• <strong>红色区域：</strong>未使用领奖码数量（流失用户）</div>
                  <div><strong>数据来源：</strong><code>consul_wechat_reward_codes</code> 按状态统计</div>
                  <div><strong>筛选条件：</strong>受时间范围 / 商户 / 活动筛选限制</div>
                  <div style="margin-top: 8px; padding: 8px; background: #e67e22; border-radius: 4px; color: #fff;">
                    <div><strong>💡 饼图解读技巧：</strong></div>
                    <div>• <strong>绿色占比大：</strong>转化效果好，活动吸引力强</div>
                    <div>• <strong>红色占比大：</strong>流失率高，需优化活动设计</div>
                    <div>• <strong>理想转化率：</strong>一般在60-80%为优秀水平</div>
                    <div>• <strong>分析维度：</strong>可按商户/活动对比转化效果</div>
                    <div style="color: #ecf0f1; font-size: 12px;">注：转化率直接影响ROI，是核心业务指标</div>
                  </div>
                </div>
                <i class="el-icon-question" style="margin-left:6px;color:#909399;cursor:help;"></i>
              </el-tooltip>
            </div>
            <div id="conversionChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 商户排行榜 -->
    <div class="ranking-section">
      <el-card>
        <div slot="header">
          <span>商户排行榜</span>
          <el-tooltip placement="top">
            <div slot="content" style="max-width: 520px; line-height: 1.5;">
              <div><strong>定义：</strong>按总参与数排序的商户活跃度排行榜（Top 10）</div>
              <div><strong>排序规则：</strong>总参与数 DESC → 独立用户数 DESC → 活跃活动数 DESC</div>
              <div><strong>数据来源：</strong><code>consul_merchants</code> JOIN <code>consul_nfc_participations</code></div>
              <div><strong>表格字段说明：</strong></div>
              <div>• <strong>总参与数：</strong>该商户所有活动的扫码参与总次数</div>
              <div>• <strong>独立用户数：</strong>参与该商户活动的不重复用户数</div>
              <div>• <strong>活跃活动数：</strong>有用户参与的活动数量</div>
              <div><strong>筛选条件：</strong>受时间范围筛选限制，不受商户筛选影响</div>
              <div style="margin-top: 8px; padding: 8px; background: #27ae60; border-radius: 4px; color: #fff;">
                <div><strong>💡 排行榜分析技巧：</strong></div>
                <div>• <strong>🥇🥈🥉 徽章：</strong>前三名用金银铜色标识</div>
                <div>• <strong>对比维度：</strong>参与热度 vs 用户覆盖 vs 活动数量</div>
                <div>• <strong>商户画像：</strong>高参与+高用户=优质商户</div>
                <div>• <strong>优化建议：</strong>低排名商户可参考头部商户运营策略</div>
                <div style="color: #ecf0f1; font-size: 12px;">注：排行榜仅显示有参与数据的商户，零参与商户不展示</div>
              </div>
            </div>
            <i class="el-icon-question" style="margin-left:6px;color:#909399;cursor:help;"></i>
          </el-tooltip>
        </div>
        <el-table :data="merchantRanking" border stripe>
          <el-table-column type="index" label="排名" width="80" align="center">
            <template slot-scope="scope">
              <span class="ranking-badge" :class="getRankingClass(scope.$index)">
                {{ scope.$index + 1 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="merchant_name" label="商户名称" align="center"></el-table-column>
          <el-table-column prop="contacts" label="联系人" align="center"></el-table-column>
          <el-table-column prop="total_attributions" label="总参与数" align="center"></el-table-column>
          <el-table-column prop="unique_users" label="独立用户数" align="center"></el-table-column>
          <el-table-column prop="active_campaigns" label="活跃活动数" align="center"></el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 导出对话框 -->
    <el-dialog title="导出数据" :visible.sync="exportDialogVisible" width="400px">
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出类型">
          <el-select v-model="exportForm.type" placeholder="请选择导出类型">
            <el-option label="全部数据" value="all"></el-option>
            <el-option label="参与统计" value="participation"></el-option>
            <el-option label="转化统计" value="conversion"></el-option>
            <el-option label="商户排行" value="ranking"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport" :loading="exporting">确定导出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  exportAnalyticsData,
  getConversionStats,
  getMerchantRanking,
  getParticipationStats,
  getTrendData
} from '@/api/nfc-analytics';
import {getCampaignList, getMerchantList} from '@/api/nfc';

export default {
  name: 'NfcAnalytics',
  data() {
    return {
      // 搜索条件
      searchForm: {
        start_date: '',
        end_date: '',
        merchant_id: null,
        campaign_id: null
      },
      dateRange: [],

      // 选项数据
      merchantOptions: [],
      campaignOptions: [],
      allCampaignOptions: [], // 存储所有活动数据

      // 统计数据
      participationStats: {},
      conversionStats: {},
      merchantRanking: [],
      trendData: [],

      // 图表实例
      trendChart: null,
      conversionChart: null,

      // 导出相关
      exportDialogVisible: false,
      exportForm: {
        type: 'all'
      },
      exporting: false,

      // 加载状态
      loading: false
    };
  },

  computed: {
    // 根据选择的商户过滤活动选项
    filteredCampaignOptions() {
      console.log('计算过滤活动选项...');
      console.log('当前选择的商户ID:', this.searchForm.merchant_id);
      console.log('所有活动数据:', this.allCampaignOptions);

      if (!this.searchForm.merchant_id) {
        console.log('没有选择商户，返回所有活动');
        return this.allCampaignOptions;
      }

      const filtered = this.allCampaignOptions.filter(campaign => {
        console.log(`活动 ${campaign.campaign_name} 的merchant_id: ${campaign.merchant_id}, 类型: ${typeof campaign.merchant_id}`);
        console.log(`选择的merchant_id: ${this.searchForm.merchant_id}, 类型: ${typeof this.searchForm.merchant_id}`);
        return campaign.merchant_id == this.searchForm.merchant_id; // 使用 == 而不是 === 来处理类型转换
      });

      console.log('过滤后的活动:', filtered);
      return filtered;
    }
  },

  async mounted() {
    // 初始化日期范围（默认最近30天）
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);

    this.dateRange = [
      this.formatDate(startDate),
      this.formatDate(endDate)
    ];
    this.handleDateChange(this.dateRange);

    // 加载基础数据
    await this.loadMerchantList();
    await this.loadCampaignList();

    // 初始化图表
    this.$nextTick(async () => {
      this.initCharts();
      // 图表初始化完成后再加载数据
      await this.loadAnalyticsData();
    });
  },

  beforeDestroy() {
    // 销毁图表实例
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.conversionChart) {
      this.conversionChart.dispose();
    }
  },

  methods: {
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 处理日期范围变化
    handleDateChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.searchForm.start_date = dateRange[0];
        this.searchForm.end_date = dateRange[1];
      } else {
        this.searchForm.start_date = '';
        this.searchForm.end_date = '';
      }
    },

    // 加载商户列表
    async loadMerchantList() {
      try {
        const result = await getMerchantList();
        console.log('商户列表API响应:', result);
        if (result.code === 0) {
          this.merchantOptions = result.data;
          console.log('商户数据:', this.merchantOptions);
        }
      } catch (e) {
        console.error('加载商户列表失败:', e);
        this.$message.error('加载商户列表失败');
      }
    },

    // 加载活动列表
    async loadCampaignList() {
      try {
        const result = await getCampaignList({ limit: 100 });
        console.log('活动列表API响应:', result);
        if (result.code === 0) {
          this.allCampaignOptions = result.data.list || [];
          console.log('所有活动数据:', this.allCampaignOptions);
          // 检查活动数据结构
          if (this.allCampaignOptions.length > 0) {
            console.log('第一个活动的数据结构:', this.allCampaignOptions[0]);
          }
        }
      } catch (e) {
        console.error('加载活动列表失败:', e);
        this.$message.error('加载活动列表失败');
      }
    },

    // 加载统计数据
    async loadAnalyticsData() {
      this.loading = true;
      try {
        // 并行加载所有统计数据
        const [
          participationResult,
          conversionResult,
          rankingResult,
          trendResult
        ] = await Promise.all([
          getParticipationStats(this.searchForm),
          getConversionStats(this.searchForm),
          getMerchantRanking({ ...this.searchForm, limit: 10 }),
          getTrendData(this.searchForm)
        ]);

        if (participationResult.code === 0) {
          this.participationStats = participationResult.data || {};
        } else {
          this.participationStats = {};
        }

        if (conversionResult.code === 0) {
          this.conversionStats = conversionResult.data || {};
        } else {
          this.conversionStats = {};
        }

        if (rankingResult.code === 0) {
          this.merchantRanking = Array.isArray(rankingResult.data) ? rankingResult.data : [];
        } else {
          this.merchantRanking = [];
        }

        if (trendResult.code === 0) {
          this.trendData = Array.isArray(trendResult.data) ? trendResult.data : [];
          this.updateTrendChart();
        } else {
          this.trendData = [];
        }

        this.updateConversionChart();

      } catch (e) {
        console.error('加载统计数据失败:', e);
        this.$message.error('加载统计数据失败');
        // 确保在出错时也设置默认值
        this.participationStats = {};
        this.conversionStats = {};
        this.merchantRanking = [];
        this.trendData = [];
      } finally {
        this.loading = false;
      }
    },

    // 商户选择变化处理
    handleMerchantChange() {
      // 清空活动选择，因为活动列表已经通过计算属性自动过滤
      this.searchForm.campaign_id = null;
    },

    // 重置搜索
    resetSearch() {
      // 重置日期范围为初始状态（最近30天）
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - 30);

      this.dateRange = [
        this.formatDate(startDate),
        this.formatDate(endDate)
      ];
      this.handleDateChange(this.dateRange);

      // 重置搜索表单
      this.searchForm = {
        start_date: this.formatDate(startDate),
        end_date: this.formatDate(endDate),
        merchant_id: null,
        campaign_id: null
      };

      // 重置数据为默认值，避免ElTable接收到错误的数据格式
      this.participationStats = {};
      this.conversionStats = {};
      this.merchantRanking = [];
      this.trendData = [];

      // 清空图表
      if (this.trendChart) {
        this.trendChart.clear();
      }
      if (this.conversionChart) {
        this.conversionChart.clear();
      }

      // 重新加载数据
      this.loadAnalyticsData();
    },

    // 获取排名样式
    getRankingClass(index) {
      if (index === 0) return 'gold';
      if (index === 1) return 'silver';
      if (index === 2) return 'bronze';
      return '';
    },

    // 初始化图表
    initCharts() {
      this.trendChart = echarts.init(document.getElementById('trendChart'));
      this.conversionChart = echarts.init(document.getElementById('conversionChart'));

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        this.trendChart && this.trendChart.resize();
        this.conversionChart && this.conversionChart.resize();
      });

      // 如果已有数据，立即更新图表
      if (this.trendData.length > 0) {
        this.updateTrendChart();
      }
      if (this.conversionStats && Object.keys(this.conversionStats).length > 0) {
        this.updateConversionChart();
      }
    },

    // 更新趋势图表
    updateTrendChart() {
      if (!this.trendChart) return;

      // 确保trendData是数组
      const trendData = Array.isArray(this.trendData) ? this.trendData : [];

      const dates = trendData.map(item => item.date || '');
      const participations = trendData.map(item => item.participations || 0);
      const uniqueUsers = trendData.map(item => item.unique_users || 0);

      const option = {
        title: {
          text: '活动参与趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['参与数', '独立用户数'],
          bottom: 0
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '参与数',
            type: 'line',
            data: participations,
            smooth: true,
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '独立用户数',
            type: 'line',
            data: uniqueUsers,
            smooth: true,
            itemStyle: { color: '#67C23A' }
          }
        ]
      };

      this.trendChart.setOption(option);
    },

    // 更新转化率图表
    updateConversionChart() {
      if (!this.conversionChart) return;

      // 确保conversionStats是对象
      const conversionStats = this.conversionStats || {};
      const usedRewards = conversionStats.used_rewards || 0;
      const unusedRewards = Math.max(0, (conversionStats.total_rewards || 0) - usedRewards);

      const option = {
        title: {
          text: '转化率分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '领奖码使用情况',
            type: 'pie',
            radius: '50%',
            data: [
              { value: usedRewards, name: '已使用', itemStyle: { color: '#67C23A' } },
              { value: unusedRewards, name: '未使用', itemStyle: { color: '#F56C6C' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.conversionChart.setOption(option);
    },

    // 处理导出
    handleExport() {
      this.exportDialogVisible = true;
    },

    // 确认导出
    async confirmExport() {
      this.exporting = true;
      try {
        const params = {
          ...this.searchForm,
          type: this.exportForm.type
        };

        const response = await exportAnalyticsData(params);

        // 处理blob响应
        if (response instanceof Blob) {
          // 创建下载链接
          const url = window.URL.createObjectURL(response);
          const link = document.createElement('a');
          link.href = url;

          // 设置文件名
          const filename = `nfc_analytics_${this.exportForm.type}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
          link.download = filename;

          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          // 释放URL对象
          window.URL.revokeObjectURL(url);

          this.$message.success('导出成功');
          this.exportDialogVisible = false;
        } else {
          // 如果不是blob响应，说明有错误
          this.$message.error('导出失败：响应格式错误');
        }
      } catch (e) {
        console.error('导出失败:', e);
        this.$message.error('导出失败：' + (e.message || '未知错误'));
      } finally {
        this.exporting = false;
      }
    }
  }
};
</script>

<style scoped>
.page-box {
  padding: 20px;
}

.search-box {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 去掉 el-form-item 的默认下边距 */
.search-box .el-form-item {
  margin-bottom: 0;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: auto;
  min-height: 80px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stats-icon.participation {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.users {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.conversion {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.campaigns {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stats-tip-icon {
  font-size: 12px;
  color: #ccc;
  cursor: help;
  margin-left: 4px;
}

.stats-tip-icon:hover {
  color: #409EFF;
}

.charts-section {
  margin-bottom: 20px;
}

.ranking-section {
  margin-bottom: 20px;
}

.ranking-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  color: #fff;
  font-weight: bold;
  font-size: 12px;
}

.ranking-badge.gold {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  color: #333;
}

.ranking-badge.silver {
  background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
  color: #333;
}

.ranking-badge.bronze {
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
}

.ranking-badge:not(.gold):not(.silver):not(.bronze) {
  background: #909399;
}

.el-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-card__header {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 20px;
  }

  .charts-section .el-col {
    margin-bottom: 20px;
  }

  .stats-content {
    flex-direction: column;
    text-align: center;
  }

  .stats-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style>
